//
//  SRLearnAlbumViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/3/31.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRLearnAlbumViewController.h"

#import "SRCommonConstants.h"
#import "FZMCCacheManager.h"
#import "SRBookRootModel.h"
#import "SRBookCatalogueModel.h"
#import "SRBookPageModel.h"
#import "SRBookPageTrackItemModel.h"
#import "SRAudioPlayerManager.h"
#import "SRSpeakingDatabaseManager.h"

#import "SRBookPageCollectionViewCell.h"
#import "UINavigationBar+Awesome.h"
#import "SRBookCatalogueListViewController.h"
#import "SRBookPageSettingView.h"
#import "SRSpeakingTestViewController.h"


@interface SRLearnAlbumViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (strong, nonatomic) UICollectionViewFlowLayout *layout;
@property (strong, nonatomic) UICollectionView *collectionView;

@property (strong, nonatomic) NSArray *items;
@property (assign, nonatomic) NSInteger currentIndex;
@property (strong, nonatomic) SRBookPageModel *currentPageModel;
@property (strong, nonatomic) SRBookPageCollectionViewCell *targetCell;

@property (assign, nonatomic) NSInteger startRepeatPageIndex;
@property (assign, nonatomic) NSInteger endRepeatPageIndex;
@property (assign, nonatomic) NSInteger startRepeatTrackIndex;
@property (assign, nonatomic) NSInteger currentRepeatTrackIndex;
@property (strong, nonatomic) SRBookPageModel *startPageModel;
@property (strong, nonatomic) SRBookPageModel *endPageModel;

@property (strong, nonatomic) SRBookPageTrackItemModel *currentTrackModel;
@property (strong, nonatomic) SRBookPageTrackItemModel *startTrackModel;
@property (strong, nonatomic) SRBookPageTrackItemModel *endTrackModel;
@property (strong, nonatomic) SRBookRootModel *bookModel;

@property (strong, nonatomic) UIView  *translateBgView;
@property (strong, nonatomic) UILabel *translateLabel;//翻译显示

@property (strong, nonatomic) UIButton *signalButton;
@property (strong, nonatomic) UIButton *repeatButton;
@property (strong, nonatomic) UIButton *settingButton;

@property (strong, nonatomic) UIView *speakContentView;//口语练习入口
@property (strong, nonatomic) UIView *speakBgTopView;
@property (strong, nonatomic) UIView *speakBgBottomView;
@property (strong, nonatomic) UILabel *pageScoreLabel;
@property (strong, nonatomic) UIView *settingBackgroundView;
@property (strong, nonatomic) SRBookPageSettingView *settingView;

@property (assign, nonatomic) CGFloat audioRate;
@property (assign, nonatomic) BOOL clickAreaShown;
@property (assign, nonatomic) BOOL translateShown;
@property (assign, nonatomic) BOOL speakingEntranceHidden;


    //连续复读
@property (strong, nonatomic) SRBookCatalogueListViewController *catalogueListVC;
@property (assign, nonatomic) SRBookPageTrackRepeatType repeatType;
@property (strong, nonatomic) UIView *multiRepeatContentView;
@property (strong, nonatomic) UILabel *repeatTipLabel;
@property (strong, nonatomic) UIButton *stopRepeatButton;
@property (strong, nonatomic) UIButton *pauseRepeatButton;
@property (assign, nonatomic) BOOL isSelectedRepeatStart;
@property (assign, nonatomic) BOOL isSelectedRepeatEnd;
@property (assign, nonatomic) BOOL shouldRepeatAgain;//再次开始复读，从最初位置开始；
@property (assign, nonatomic) BOOL isPause;//暂停状态，再次开始复读，
@property (assign, nonatomic) BOOL isMultiRepeating;//正在复读中

@end

@implementation SRLearnAlbumViewController

- (void)dealloc {
    [SRAudioPlayerManager sharedInstance].audioPlayerCompletedBlock = nil;
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupData];
    [self setupView];
    [self setupNavigationBarButtonItem];
    [self setupBottomView];
    [self setupSpeakEntranceView];
    [self setupRepeatView];
    
    if (!self.bookModel) {
        [self failedLoadingViewWithTitle:@"读取课本信息失败，请重新下载试试"];
    }
    
    if (self.currentPageModel) {
        [self updateSpeakingEntranceStatusWithPageScore:self.currentPageModel.pageScore];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    
    if (self.currentIndex > 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar lt_reset];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [SRAudioPlayerManager sharedInstance].audioPlayerCompletedBlock = nil;
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
    
    [self saveLastPageToDatabase];
}

#pragma mark - init

- (void)setupData {
    //从文档中读取教材信息
    self.clickAreaShown = YES;
    self.translateShown = YES;
    self.audioRate = [SRAudioPlayerManager sharedInstance].audioRate;
    self.repeatType = SRBookPageTrackRepeatTypeNone;
    
    SRBookRootModel *bookRootModel = [[FZMCCacheManager defaultManager] readBookModelFromDocumentWithBookID:self.bookID];
    if (bookRootModel) {
        
            //给page添加单元id catalogue_id
        NSArray *catalogueArray = bookRootModel.catalogues;
        NSArray *pagesArray = bookRootModel.pages;
        
        for (int i = 0; i < [catalogueArray count]; ++ i) {
            SRBookCatalogueModel *catalogueModel = [catalogueArray objectAtIndex:i];
            for (int j = 0; j < [pagesArray count]; ++ j) {
                SRBookPageModel *pageModel = pagesArray[j];
                NSArray *cataPageIDs = [catalogueModel.page_id splitWith:@","];
                if ([cataPageIDs containsObject:pageModel.pageID]) {
                    pageModel.catalogue_id = catalogueModel.catalogue_id;
                }
            }
        }
        
        
        self.bookModel = bookRootModel;
        self.items = self.bookModel.pages;

        NSArray *saveArray = [SRSpeakingDatabaseManager searchBookModelWithBookID:self.bookID];
        if ([saveArray count] > 0) {
            FZHomeCourseModel *saveBookModel = [saveArray objectAtIndex:0];
            if (saveBookModel.identifier && saveBookModel.lastPageIndex > 0 && saveBookModel.lastPageIndex < [self.bookModel.pages count]) {
                self.currentIndex = saveBookModel.lastPageIndex;
                self.currentPageModel = self.items[self.currentIndex];
                self.currentPageModel.pageScore = [self getPageScoreFromDBWithPage:self.currentPageModel.catalogue_id];
            }
        }
        
        if (self.currentIndex > 0) {
                //已经获取上一次记录
        }
        else if (self.bookModel.pages && [self.bookModel.pages count] > 0) {
            self.currentPageModel = [self.items firstObject];
            self.currentIndex = 0;
            self.currentPageModel.pageScore = [self getPageScoreFromDBWithPage:self.currentPageModel.pageID];
        }
    }
}

- (void)setupView {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor clearColor]];
    
    self.view.backgroundColor = css.color_2;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0.f;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.layout = layout;
    
    collectionView.backgroundColor = [UIColor clearColor];
    collectionView.pagingEnabled = YES;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    
    [collectionView registerNib:[UINib nibWithNibName:kSRBookPageCollectionViewCell bundle:nil] forCellWithReuseIdentifier:kSRBookPageCollectionViewCell];
    
    collectionView.dataSource = self;
    collectionView.delegate = self;
    
    [self.view addSubview:collectionView];
    
        //    CGFloat bottomControlHeight = 44.f;
    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.leading.equalTo(self.view).with.offset(0.0f);
        make.trailing.equalTo(self.view).with.offset(0.0f);
        make.top.equalTo(self.view).with.offset(0.0f);
        make.bottom.equalTo(self.view).with.offset(0);
    }];
    self.collectionView = collectionView;
    
    
    self.translateLabel = [[UILabel alloc] init];
    self.translateLabel.textColor = css.color_4;
    self.translateLabel.font = css.fontOfH7;
    self.translateLabel.textAlignment = NSTextAlignmentCenter;
//    self.translateLabel.backgroundColor = [UIColor redColor];//[UIColor colorWithWhite:0 alpha:0.6];
//    self.translateLabel.layer.masksToBounds = YES;
//    self.translateLabel.layer.cornerRadius = 4;
    self.translateLabel.numberOfLines = 0;
//    self.translateLabel.hidden = YES;
    
    UIView *translateBgView = [[UIView alloc] init];
    translateBgView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
    translateBgView.layer.masksToBounds = YES;
    translateBgView.layer.cornerRadius = 5;
    self.translateBgView = translateBgView;
    self.translateBgView.hidden = YES;
    
    self.translateLabel.userInteractionEnabled = NO;
    self.translateBgView.userInteractionEnabled = NO;
    
    [translateBgView addSubview:self.translateLabel];
    [self.translateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(translateBgView).offset(10);
        make.trailing.equalTo(translateBgView).offset(-10);
        make.top.equalTo(translateBgView).offset(10);
        make.bottom.equalTo(translateBgView).offset(-10);
    }];
    
    [self.view addSubview:translateBgView];
    
    [translateBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.centerX.equalTo(self.view.mas_centerX);
        make.leading.greaterThanOrEqualTo(self.view).offset(15);
        make.trailing.lessThanOrEqualTo(self.view).offset(-15);
    }];

    WEAKSELF
    
    self.settingBackgroundView = [[UIView alloc] init];
    self.settingBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [self.settingBackgroundView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        [weakSelf onTapSettingBgView:nil];
    }];
    
    [self.view addSubview:self.settingBackgroundView];
    
    
    self.settingView = [[[NSBundle mainBundle] loadNibNamed:@"SRBookPageSettingView" owner:nil options:nil] firstObject];
    
    [self.settingBackgroundView addSubview:self.settingView];
    self.settingView.audioRate = self.audioRate;
    
    [self.settingBackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.settingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.settingBackgroundView);
        make.height.mas_equalTo(333);
    }];
    
    self.settingView.speedValueDidChangeBlock = ^(CGFloat speedValue) {
        weakSelf.audioRate = speedValue;
        [[SRAudioPlayerManager sharedInstance] setAudioRate:speedValue];
    };
    
    self.settingView.clickAreaShowValueDidChangeBlock = ^(BOOL areaShown) {
        weakSelf.clickAreaShown = areaShown;
    };
    
    self.settingView.showTranslateValueDidChangeBlock = ^(BOOL showTranslate) {
        weakSelf.translateShown = showTranslate;
    };
    
    self.settingBackgroundView.hidden = YES;
}

- (void)setupSpeakEntranceView {
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
    self.speakContentView = [[UIView alloc] init];
    self.speakContentView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.speakContentView];
    [self.speakContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(75);
        make.leading.equalTo(self.view).offset(15);
        make.bottom.equalTo(self.view).offset(-15);
    }];
    

    UIView *circleView = [[UIView alloc] init];
    circleView.backgroundColor = [UIColor clearColor];
    circleView.layer.masksToBounds = YES;
    circleView.layer.cornerRadius = 30;
    
    [self.speakContentView addSubview:circleView];
    [circleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.speakContentView.mas_trailing);
        make.top.equalTo(self.speakContentView.mas_top).offset(5);
        make.width.height.mas_equalTo(60);
    }];
    
    UIImageView *topImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"speakingEnTop_icon"]];
    [self.speakContentView addSubview:topImageView];
    
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.equalTo(self.speakContentView);
        make.width.height.mas_equalTo(30);
    }];
    
    UIView *topView = [[UIView alloc] init];
//    topView.layer.masksToBounds = YES;
//    topView.layer.cornerRadius = 30;
    self.speakBgTopView = topView;
    self.speakBgTopView.backgroundColor = css.color_7;
    [circleView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(circleView);
        make.top.equalTo(circleView);
        make.height.mas_equalTo(40);
    }];
    
    UIView *bottomView = [[UIView alloc] init];
    self.speakBgBottomView = bottomView;
    self.speakBgBottomView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
    [circleView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(circleView);
        make.bottom.equalTo(circleView);
        make.height.mas_equalTo(20);
    }];
    UILabel *scoreLabel = [[UILabel alloc] init];
    scoreLabel.textColor = css.color_2;
    scoreLabel.font = css.fontOfH6;
    scoreLabel.textAlignment = NSTextAlignmentCenter;
    scoreLabel.text = @"配音";
    self.pageScoreLabel = scoreLabel;
    
    [circleView addSubview:scoreLabel];
    [scoreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(circleView);
        make.bottom.equalTo(circleView.mas_bottom).offset(-20);
        make.height.mas_equalTo(30);
    }];
    
    UILabel *testLabel = [[UILabel alloc] init];
    testLabel.textColor = css.color_4;
    testLabel.font = css.fontOfH8;
    testLabel.textAlignment = NSTextAlignmentCenter;
    testLabel.text = @"测评";
//    testLabel.backgroundColor = [UIColor redColor];
    
    [circleView addSubview:testLabel];
    [testLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(20);
        make.leading.equalTo(circleView);
        make.trailing.equalTo(circleView);
        make.top.equalTo(circleView.mas_bottom).offset(-20);
    }];
    
    WEAKSELF
    [self.speakContentView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        [weakSelf onSpeakEntranceButton:nil];
    }];
}

- (void)setupRepeatView {
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.multiRepeatContentView = [[UIView alloc] init];
    self.multiRepeatContentView.backgroundColor = css.color_2;
    
    [self.view addSubview:self.multiRepeatContentView];
    [self.multiRepeatContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(48);
    }];
    
    self.multiRepeatContentView.hidden = YES;
    
    self.repeatTipLabel = [[UILabel alloc] init];
    self.repeatTipLabel.textColor = css.color_4;
    self.repeatTipLabel.text = @"请点击选择复读起点区域";
    self.repeatTipLabel.font = css.fontOfH3;
    
    [self.multiRepeatContentView addSubview:self.repeatTipLabel];
    [self.repeatTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.multiRepeatContentView).offset(15);
        make.top.bottom.equalTo(self.multiRepeatContentView);
    }];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = css.fontOfH3;
    cancelButton.layer.masksToBounds = YES;
    cancelButton.layer.cornerRadius = 20;
    [cancelButton setBackgroundImage:[UIImage imageWithColor:css.color_7] forState:UIControlStateNormal];

    [cancelButton addTarget:self action:@selector(onCancelMultiRepeatButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.multiRepeatContentView addSubview:cancelButton];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.multiRepeatContentView).offset(-15);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(75);
        make.centerY.equalTo(self.multiRepeatContentView);
    }];
    
    self.stopRepeatButton = [self createCircleButtonWithTitle:@"停止" action:@selector(onStopRepeatButton:)];
    self.pauseRepeatButton = [self createCircleButtonWithTitle:@"暂停" action:@selector(onPauseRepeatButton:)];
    self.stopRepeatButton.layer.cornerRadius = 30;
    self.pauseRepeatButton.layer.cornerRadius = 30;
    
    [self.stopRepeatButton setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHex:0xFF3C00]] forState:UIControlStateNormal];
    [self.pauseRepeatButton setBackgroundImage:[UIImage imageWithColor:css.color_7] forState:UIControlStateNormal];

    [self.stopRepeatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(60);
        make.leading.equalTo(self.view).offset(15);
        make.bottom.equalTo(self.view).offset(-15);
    }];
    
    [self.pauseRepeatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(60);
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-15);
    }];
    
    self.stopRepeatButton.hidden = YES;
    self.pauseRepeatButton.hidden = YES;
}



- (void)setupNavigationBarButtonItem {
    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setImage:[UIImage imageNamed:@"icon_catagolue"] forState:UIControlStateNormal];
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton addTarget: self action: @selector(onCatagolueListButton:) forControlEvents: UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    [self setRightBarButtonItem:rightBarItem];
}

- (void)setupBottomView {
    self.signalButton = [self createCircleButtonWithTitle:@"单句" action:@selector(onSignalButton:)];
    self.repeatButton = [self createCircleButtonWithTitle:@"复读" action:@selector(onRepeatButton:)];
    self.settingButton = [self createCircleButtonWithTitle:@"设置" action:@selector(onSettingButton:)];
    
    [self.settingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(40);
        make.trailing.equalTo(self.view).offset(-15);
        make.bottom.equalTo(self.view).offset(-15);
    }];
    
    [self.repeatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(40);
        make.trailing.equalTo(self.settingButton.mas_leading).offset(-15);
        make.bottom.equalTo(self.view).offset(-15);
    }];
    
    [self.signalButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(40);
        make.trailing.equalTo(self.repeatButton.mas_leading).offset(-15);
        make.bottom.equalTo(self.view).offset(-15);
    }];
    
}

- (UIButton *)createCircleButtonWithTitle:(NSString *)title action:(SEL)action {
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitleColor:css.color_4 forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    button.titleLabel.font = css.fontOfH7;
    button.frame = CGRectMake(0, 0, 40, 40);
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 20;
    
    UIColor *bgColor = [UIColor colorWithWhite:0 alpha:0.6];
    [button setBackgroundImage:[UIImage imageWithColor:bgColor] forState:UIControlStateNormal];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
    
    return button;
}

#pragma mark - Event

- (void)onCatagolueListButton:(id)sender {
    self.settingBackgroundView.hidden = YES;
    WEAKSELF
    if (!self.catalogueListVC) {
        SRBookCatalogueListViewController *vc = [[SRBookCatalogueListViewController alloc] init];
        vc.catalogues = self.bookModel.catalogues;
        vc.didSelectedCatalogueBlock = ^(SRBookCatalogueModel *catalogueModel) {
            [weakSelf scrollToCatalogue:catalogueModel];
        };
        
        self.view.superview.backgroundColor = [UIColor clearColor];
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        self.catalogueListVC = vc;
    }
    
    [self presentViewController:self.catalogueListVC animated:YES completion:^{
        
    }];
}

- (void)scrollToCatalogue:(SRBookCatalogueModel *)catalogueModel {
    [self scrollToPageWithPageID:catalogueModel.firstPageID];
}

- (void)scrollToPageWithPageID:(NSString *)pageID {
    if (!pageID) {
        return;
    }
    
    NSInteger scrollIndex = -1;
    for (int i = 0; i < [self.items count]; ++ i) {
        SRBookPageModel *pageModel = self.items[i];
        if ([pageID isEqualToString:pageModel.pageID]) {
            scrollIndex = i;
            self.currentPageModel = pageModel;
            break;
        }
    }
    
    if (scrollIndex >= 0) {
        
        self.currentPageModel.pageScore = [self getPageScoreFromDBWithPage:self.currentPageModel.pageID];
        [self updateSpeakingEntranceStatusWithPageScore:self.currentPageModel.pageScore];
        
        self.currentIndex = scrollIndex;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:scrollIndex inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }
}

- (void)onSignalButton:(id)sender {
    if (self.repeatType == SRBookPageTrackRepeatTypeSingle) {
            //关闭
        self.repeatType = SRBookPageTrackRepeatTypeNone;
        [self showHUDHintWithText:@"您已关闭单句复读模式"];
        [self.signalButton setTitle:@"单句" forState:UIControlStateNormal];
    } else {
            //开启
        self.repeatType = SRBookPageTrackRepeatTypeSingle;
        [self showHUDHintWithText:@"您已开启单句复读模式"];
        [self.signalButton setTitle:@"连续" forState:UIControlStateNormal];
    }
    
}
- (void)onRepeatButton:(id)sender {
    self.repeatType = SRBookPageTrackRepeatTypeMultiSentence;
    
    [self setBaseControlButtonHidden:YES];
    self.multiRepeatContentView.hidden = NO;
    [self.view bringSubviewToFront:self.multiRepeatContentView];
    
}

- (void)onSettingButton:(id)sender {
    
        //todo
//    NSString *dirPath = [FZMCCacheManager recordPageDirPathWithPageID:self.currentPageModel.pageID bookID:self.bookID];
//    [FZMCCacheManager removefolderFileCache:dirPath];
    
    if (self.settingBackgroundView.hidden) {
        self.settingBackgroundView.hidden = NO;
        [self.view bringSubviewToFront:self.settingBackgroundView];
    } else {
        self.settingBackgroundView.hidden = YES;
    }
}


- (void)onSpeakEntranceButton:(id)sender {
    
    NSString *currentCatalogueID = self.currentPageModel.catalogue_id;
    SRBookCatalogueModel *currentCatalogueModel = nil;
    for (SRBookCatalogueModel *catalogueModel in self.bookModel.catalogues) {
        if ([catalogueModel.catalogue_id isEqualToString:currentCatalogueID]) {
            currentCatalogueModel = catalogueModel;
            break;
        }
    }
    
    NSMutableArray *trackArray = [@[] mutableCopy];
    for (int j = 0; j < [self.items count]; ++ j) {
        SRBookPageModel *pageModel = self.items[j];
        if ([pageModel.catalogue_id isEqualToString:currentCatalogueID] && [pageModel.tracks count] > 0){
            [trackArray addObjectsFromArray:pageModel.tracks];
        }
    }
    
    SRSpeakingTestViewController *vc = [[SRSpeakingTestViewController alloc] init];
    vc.items = trackArray;//self.currentPageModel.tracks;
    vc.catalogueModel = currentCatalogueModel;
    vc.bookID = self.bookID;
    vc.bookName = self.bookModel.name;
    
    WEAKSELF
    vc.pageSpeakingTestScoreBlock = ^(NSInteger score) {
        [weakSelf updateSpeakingEntranceStatusWithPageScore:score];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)onTapSettingBgView:(id)sender {
    self.settingBackgroundView.hidden = YES;
}

- (void)onCancelMultiRepeatButton:(id)sender {
    self.repeatType = SRBookPageTrackRepeatTypeNone;
    self.multiRepeatContentView.hidden = YES;
    [self setBaseControlButtonHidden:NO];
}

- (void)onStopRepeatButton:(id)sender {
    [self setMultiRepeatControlButtonHidden:YES];
    [self setBaseControlButtonHidden:NO];
    
    self.repeatType = SRBookPageTrackRepeatTypeNone;
    
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
    
    self.isSelectedRepeatStart = NO;
    self.isSelectedRepeatEnd = NO;
    self.startRepeatPageIndex = 0;
    self.endTrackModel = nil;
    self.endPageModel = nil;
    self.shouldRepeatAgain = NO;
    self.endRepeatPageIndex = 0;
    
}

- (void)onPauseRepeatButton:(id)sender {
    if (self.isPause) {
        self.isPause = NO;
        [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
    } else {
        self.isPause = YES;
        [[SRAudioPlayerManager sharedInstance] pauseRecordAudio];
    }
}

- (void)setTranslateShown:(BOOL)translateShown {
    _translateShown = translateShown;
    
    self.translateBgView.hidden = !translateShown;
}

- (void)setClickAreaShown:(BOOL)clickAreaShown {
    _clickAreaShown = clickAreaShown;
    
    if (self.currentIndex >= 0 && self.currentIndex < [self.items count]) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
        SRBookPageCollectionViewCell *cell = (SRBookPageCollectionViewCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
        if (cell && [cell isKindOfClass:[SRBookPageCollectionViewCell class]]) {
            cell.clickAreaShow = clickAreaShown;
        }
    }
}

- (void)setSpeakingEntranceHidden:(BOOL)speakingEntranceHidden {
    _speakingEntranceHidden = speakingEntranceHidden;
    
    self.speakContentView.hidden = speakingEntranceHidden;
}

- (void)updateSpeakingEntranceStatusWithPageScore:(NSInteger)score {
    if (score > 0) {
            //有分数显示
        self.pageScoreLabel.text = [NSString stringWithFormat:@"%d", (int)score];
        self.pageScoreLabel.textColor = [FZStyleSheet currentStyleSheet].color_4;
        self.pageScoreLabel.font = [FZStyleSheet currentStyleSheet].fontOfH1;
        self.speakBgTopView.backgroundColor = [FZStyleSheet currentStyleSheet].color_8;
        self.speakBgBottomView.backgroundColor = [FZStyleSheet currentStyleSheet].color_7;
    }
    else {
            //没分数
        self.speakBgTopView.backgroundColor = [FZStyleSheet currentStyleSheet].color_7;
        self.speakBgBottomView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];

        self.pageScoreLabel.textColor = [FZStyleSheet currentStyleSheet].color_2;
        self.pageScoreLabel.font = [FZStyleSheet currentStyleSheet].fontOfH6;
        self.pageScoreLabel.text = @"配音";
    }
}

//获取单页的总分
- (NSInteger )getPageScoreFromDBWithPage:(NSString *)pageID {
    NSString *data_id = [NSString stringWithFormat:@"%@_%@", self.bookID, pageID];
    NSArray *scoreArray = [SRSpeakingDatabaseManager searchMyDraftModelWithDataID:data_id];
    if (scoreArray.count > 0) {
        SRSpeakingTestModel *unpubModel = [scoreArray firstObject];
        if (unpubModel && unpubModel.totalScore) {
            return [unpubModel.totalScore integerValue];
        }
    }
    
    return 0;
}

- (void)setBaseControlButtonHidden:(BOOL)isHidden {
    self.speakContentView.hidden = isHidden;
    self.signalButton.hidden = isHidden;
    self.repeatButton.hidden = isHidden;
    self.settingButton.hidden = isHidden;
}

- (void)setMultiRepeatControlButtonHidden:(BOOL)isHidden {
    self.stopRepeatButton.hidden = isHidden;
    self.pauseRepeatButton.hidden = isHidden;
}

- (void)saveLastPageToDatabase {
    [SRSpeakingDatabaseManager updateBookModel:self.bookID pageIndex:self.currentIndex pageID:self.currentPageModel.pageID];
}

#pragma mark -  UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.items.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SRBookPageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kSRBookPageCollectionViewCell forIndexPath:indexPath];
    cell.clickAreaShow = self.clickAreaShown;
    
    SRBookPageModel *item = self.items[indexPath.item];
    WEAKSELF
    cell.playAudioTrackBlock = ^(SRBookPageTrackItemModel *trackModel, NSInteger trackIndex) {
        [weakSelf onSelectedPlayAudioWithTrackModel:trackModel trackIndex:trackIndex];
    };
    
    cell.allTracksDidFinishPlayBlock = ^(void){
        [weakSelf playNextPageModel];
    };
    
    [cell updateCellInfo:item bookID:self.bookID];
    
    return cell;
}

#pragma mark -  UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    NSIndexPath *indexPath = [self currentVisiableIndexPathWithOffset:offset];
    if (!indexPath || self.currentIndex == indexPath.item) {
        return;
    }
    self.currentIndex = indexPath.item;
    
    SRBookPageModel *item = self.items[indexPath.item];
    self.currentPageModel = item;
    
    self.currentPageModel.pageScore = [self getPageScoreFromDBWithPage:item.catalogue_id];
    [self updateSpeakingEntranceStatusWithPageScore:self.currentPageModel.pageScore];
}

//- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
//    NSLog(@"******scrollViewDidEndScrollingAnimation");
//}

- (NSIndexPath *)currentVisiableIndexPathWithOffset:(CGPoint)offset {
    NSIndexPath *resultIndexPath = nil;
    NSArray *visiableItems = [self.collectionView indexPathsForVisibleItems];
    if (visiableItems && visiableItems.count > 0) {
        resultIndexPath = [visiableItems lastObject];
        NSArray *visiableCells = [self.collectionView visibleCells];
        for (UICollectionViewCell *cell in visiableCells) {
            CGPoint cellOrign = cell.frame.origin;
            if (CGPointEqualToPoint(cellOrign, offset)) {
                resultIndexPath = [self.collectionView indexPathForCell:cell];
                break;
            }
        }
    }
    
    return resultIndexPath;
}

#pragma mark - Audio Play Manager

- (void)onSelectedPlayAudioWithTrackModel:(SRBookPageTrackItemModel *)trackModel trackIndex:(NSInteger)trackIndex {
    
    if (self.repeatType == SRBookPageTrackRepeatTypeSingle) {
            //单句复读
        WEAKSELF
        self.currentTrackModel = trackModel;
        [SRAudioPlayerManager sharedInstance].audioPlayerCompletedBlock = ^(BOOL finish) {
            if (weakSelf.currentTrackModel && weakSelf.repeatType == SRBookPageTrackRepeatTypeSingle) {
                [weakSelf playAudioWithTrackModel:weakSelf.currentTrackModel];
            }
        };
        
        [self playAudioWithTrackModel:trackModel];
    }
    else if (self.repeatType == SRBookPageTrackRepeatTypeMultiSentence) {
            //多句连续复读；
        if (!self.isSelectedRepeatStart) {
                //没有选择开始起点，则选择
            self.isSelectedRepeatStart = YES;
            self.startRepeatPageIndex = self.currentIndex;
            self.startRepeatTrackIndex = trackIndex;
            
            self.startTrackModel = trackModel;
            self.repeatTipLabel.text = @"请点击选择复读终点区域";

        } else {
                //已经选择了起点，
            if (!self.isSelectedRepeatEnd) {
                    //没有选择终点，则选择
                if ([trackModel.track_id integerValue] <= [self.startTrackModel.track_id integerValue]) {
                    [self showHUDErrorMessage:@"复读终点只能选择起点后面的位置"];
                } else {
                    self.isSelectedRepeatEnd = YES;
                    self.endRepeatPageIndex = self.currentIndex;
                    self.endTrackModel = trackModel;
                    
                    [self setMultiRepeatControlButtonHidden:NO];
                    self.multiRepeatContentView.hidden = YES;
                        //选择终点后，则开始复读
                    [self startMultiTrackRepeatMode];
                }
                
            } else {
                    //终点已经选择，则开始复读
                if (self.isMultiRepeating) {
                    self.currentRepeatTrackIndex = trackIndex;
                    NSString *nextTrackID = [NSString stringWithFormat:@"%@", trackModel.track_id];
                    NSString *endTrackID = [NSString stringWithFormat:@"%@", self.endTrackModel.track_id];
                    if ([nextTrackID isEqualToString:endTrackID]) {
                        self.shouldRepeatAgain = YES;
                    }
                    
                    [self playAudioWithTrackModel:trackModel];
                } else {
                        //若没开始则开始复读
                    [self startMultiTrackRepeatMode];
                }
            }
        }
        
    } else {
            //播放单句
        self.currentTrackModel = trackModel;
        
        [SRAudioPlayerManager sharedInstance].audioPlayerCompletedBlock = ^(BOOL finish) {
            
        };
        [self playAudioWithTrackModel:trackModel];
    }
}



- (void)playNextPageModel {
        //先滚动到下一页，并且从第一个tack开始播放
    ++self.currentIndex;
//    NSLog(@"******before playNextPageModel currentIndex:%d", self.currentIndex);

    if (self.currentIndex > self.endRepeatPageIndex) {
            //重复开始
        [self startMultiTrackRepeatMode];
        return;
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
            //滚动到当前页
//    NSLog(@"******before playNextPageModel scrollToItemAtIndexPath");

    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];

    
    [self performSelector:@selector(delayPlayNextPageCellFirstTrack) withObject:nil afterDelay:0.5];
}

- (void)delayPlayNextPageCellFirstTrack {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
    SRBookPageCollectionViewCell *cell = (SRBookPageCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
//    NSLog(@"******playNextPageModel cellForItemAtIndexPath:%@", cell);
    
    if (cell) {
        self.targetCell = cell;
        [cell playTrackModelWithIndex:0];
    }
}


    //开始多句复读模式
- (void)startMultiTrackRepeatMode {
    self.isMultiRepeating = YES;
    WEAKSELF
    [SRAudioPlayerManager sharedInstance].audioPlayerCompletedBlock = ^(BOOL finish) {
            //若需要重复播放，则继续
        if (weakSelf.shouldRepeatAgain) {
                //从起点播放
            weakSelf.shouldRepeatAgain = NO;
            [weakSelf playMutilRepeatStartTrack];
        } else {
            ++self.currentRepeatTrackIndex;
            [weakSelf performSelectorOnMainThread:@selector(delayPlayNextCell) withObject:nil waitUntilDone:0];
        }
    };
    
    [self playMutilRepeatStartTrack];
}

- (void)delayPlayNextCell {

//    NSLog(@"******startMultiTrackRepeatMode .audioPlayerCompletedBlock cell:%@ row:%d", cell, indexPath.row);
    if (self.targetCell) {
        [self.targetCell playTrackModelWithIndex:self.currentRepeatTrackIndex];
    } else {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
        SRBookPageCollectionViewCell *cell = (SRBookPageCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        if (cell) {
            [cell playTrackModelWithIndex:self.currentRepeatTrackIndex];
        }
    }
}

- (void)playMutilRepeatStartTrack {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.startRepeatPageIndex inSection:0];
    if (self.currentIndex != self.startRepeatPageIndex) {
            //滚动到当前页
        self.currentIndex = self.startRepeatPageIndex;
//        NSLog(@"******before playMutilRepeatStartTrack scrollToItemAtIndexPath cell");
        [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    }
    
    [self performSelector:@selector(delayPlayCellTrack) withObject:nil afterDelay:0.5];
}

- (void)delayPlayCellTrack {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.startRepeatPageIndex inSection:0];

    SRBookPageCollectionViewCell *cell = (SRBookPageCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
//    NSLog(@"******playMutilRepeatStartTrack cellForItemAtIndexPath cell:%@ row:%d", cell, indexPath.row);
    
    if (cell) {
        self.targetCell = cell;
        [cell playTrackModelWithIndex:self.startRepeatTrackIndex];
    }
}

- (void)playAudioWithTrackModel:(SRBookPageTrackItemModel *)trackModel {
    if (self.translateShown) {
        if (trackModel.track_genre && [trackModel.track_genre length] > 0) {
            self.translateLabel.text = trackModel.track_genre;
            self.translateBgView.hidden = NO;
        } else {
            self.translateLabel.text = @"";
            self.translateBgView.hidden = YES;
        }
    }
    
    NSString *mp3Path = [FZMCCacheManager mp3PathWithName:trackModel.mp3name bookID:self.bookID];
    [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFilePath:mp3Path startTime:[trackModel.track_austart doubleValue] endTime:[trackModel.track_auend doubleValue]];
    [[SRAudioPlayerManager sharedInstance] startPlayRecordAudio];
}

@end
